package bm13;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/8/15 19:54
 * BM13. 判断链表是否回文
 * https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f?tpId=295&tqId=1008769&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj
 */
public class Solution {

    // 判断链表是否回文
    public boolean isPail (ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        // 先找到链表的中间节点
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        // 此时 slow 指向中间节点(偶数个节点则为中间两个节点左侧节点, 奇数则为中间节点)
        // 反转后半段
        slow.next = reverse(slow.next);
        slow = slow.next;
        // 判断是否回文
        ListNode cur = head;
        while (slow != null) {
            if (cur.val != slow.val) {
                return false;
            }
            cur = cur.next;
            slow = slow.next;
        }
        return true;
    }

    // 反转链表
    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode curNext = cur.next;
            cur.next = pre;
            pre = cur;
            cur = curNext;
        }
        return pre;
    }

    private class ListNode {
        int val;
        ListNode next = null;
        public ListNode(int val) {
            this.val = val;
        }
    }
}
